<?php

namespace app\common\middleware;

use app\common\service\UserService;
use ReflectionClass;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class ApiAccessAuth implements MiddlewareInterface
{
    
    /**
     * api鉴权
     * @param Request $request
     * @param callable $handler
     * @return Response
     * @throws \ReflectionException
     */
    public function process(Request $request, callable $handler): Response
    {
        $controller = new ReflectionClass($request->controller);
        $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];
        if (!in_array($request->action, $noNeedLogin)) {
            
            if (empty(UserService::getId())) {
                return json(['code' => 10001, 'msg' => '登录失效']);
            }
        }
        return $handler($request);
    }
}